<template>
  <div class="container">
<!--    <el-alert  style="padding: 0px"-->
<!--               type="warning"    effect="dark"-->
<!--               :closable="false">-->
<!--      <i class="el-icon-info"> 日清存在异常数据，无法日清</i>-->
<!--    </el-alert>-->
    <!-- 查询区域 -->
    <el-row style="height:100%;">
      <el-col :span="4" style="height:100%;">
        <div class="tree-container">
          <h3>所属供应商</h3>
          <el-input placeholder="输入供应商名称进行过滤"
                    v-model="treeFilter"
                    class="tree-filter"
                    style="margin:10px;width:80%"/>
          <el-tree
            ref="tree"
            highlight-current
            default-expand-all
            node-key="id"
            :expand-on-click-node="false"
            :data="treeData"
            :props="defaultProps"
            :filter-node-method="handleTreeFilter"
            @node-click="handleTreeNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20">
        <el-row :gutter="18">
          <el-header style="text-align: right; border-bottom: black ; margin-right: 10px">
            <el-form
              class="input-form" label-position="right" label-width="20px" ref="editForm"
              :model="query"
            >
              <el-col :span="6">
                <el-form-item prop="balanceDate">
                  <el-date-picker :disabled="formDisabled" v-model="query.balanceDate" type="date"
                                  :format="dates.defaultDatePattern"
                                  @change="warehouseChange"
                                  :picker-options="dates.pickerOptions.date"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="" prop="deptId" >
                  <el-select v-model="query.deptId" filterable disabled>
                    <el-option
                      v-for="item in deptIds"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="" prop="warehouseId">
                  <el-select v-model="query.warehouseId" filterable :disabled="flagAllData"  @change="warehouseChange">
                    <el-option
                      v-for="item in warehouses"
                      :key="item.id"
                      :label="item.warehouseName"
                      :value="item.id"
                     >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-button type="warning" @click="searchResult">重新日结</el-button>
            </el-form>
          </el-header>
          <hr>
        </el-row>
        <el-collapse v-model="activeNames">
          <el-collapse-item title="汇总数据" name="2">
        <el-form
          class="input-form" label-position="right" label-width="110px" ref="editForm"
          :model="form"
        >
          <el-row :gutter="18" style="margin-top: 20px">

            <el-col :span="4">
              <el-form-item label="期初数量" prop="qtyBeginSum">
                <el-input v-model="form.qtyBeginSum" disabled placeholder="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="期末数量" prop="qtyEndSum">
                <el-input v-model="form.qtyEndSum" disabled placeholder="0"/>
              </el-form-item>
            </el-col>

            <el-col :span="4">
              <el-form-item label="入库数量" prop="qtyInSum">
                <el-input v-model="form.qtyInSum" disabled placeholder="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="出库数量" prop="qtyOutSum">
                <el-input v-model="form.qtyOutSum" disabled placeholder="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="消耗数量" prop="qtyConsumeOutSum">
                <el-input v-model="form.qtyConsumeOutSum" disabled placeholder="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="计费数量" prop="qtyChargingSum">
                <el-input v-model="form.qtyChargingSum" disabled placeholder="0"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="18">
            <el-col :span="4">
              <el-form-item label="期初金额" prop="amountBeginSum">
                <el-input v-model="form.amountBeginSum" disabled placeholder="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="期末金额" prop="amountEndSum">
                <el-input v-model="form.amountEndSum" disabled placeholder="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="入库金额" prop="amountInSum">
                <el-input v-model="form.amountInSum" disabled placeholder="0"/>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="出库金额" prop="amountOutSum">
                <el-input v-model="form.amountOutSum" disabled placeholder="0"/>
              </el-form-item>
            </el-col>


            <el-col :span="4">
              <el-form-item label="消耗金额" prop="amountConsumeOutSum">
                <el-input v-model="form.amountConsumeOutSum" disabled placeholder="0"/>
              </el-form-item>
            </el-col>

            <el-col :span="4">
              <el-form-item label="计费金额" prop="amountChargingSum">
                <el-input v-model="form.amountChargingSum" disabled placeholder="0"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
          </el-collapse-item>
        </el-collapse>
        <div v-show="showTabs" style="height:700px;overflow:visible;">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="品规日清" name="specList">
              <div style="height:700px;overflow:auto;">
              <data-view
                ref="dataView"
                propViewKey="dept_daily_balance_item"
                :propShowToolBar="true"
                :propPreQueryWrapper="cpPerQueryWrapper"
                :propInitData="selectedTreeNode"
                @after-load="afterLoad"
              />
              </div>
            </el-tab-pane>
            <el-tab-pane label="收费日清" name="chargeList">
              <div style="height:700px;overflow:auto;">
              <data-view
             ref="dv"
             propViewKey="his_daily_balance_item"
              :propPreQueryWrapper="cpPerQueryWrapper"
              :propShowToolBar="true"
             :propInitData="selectedTreeNode"
              />
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>

export default {
  name: 'dailybalance',
  data() {
    return {
      flagAllData: true,
      activeNames: ['1', '2', '12'],
      input: '',
      treeData: [],
      activeName: 'specList',
      showTabs: true,
      treeFilter: '',
      selectedTreeNode: {},
      treeEntry: '/base/supplier/all',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      nowDate: '',
      form: {},
      query: {},
      deptIds: [],
      warehouses: [],
      formDisabled: true,
      loading: false,
      tableData: [],
      tableCustom: {
        storage: true
      },
      tableToolbar: {
        custom: true,
        slots: {
          buttons: 'toolbar_buttons'
        }
      },
      tableColumn: [
        { type: 'seq', width: 60 },
        { field: 'matrName', title: '品名'},
        { field: 'matrName', title: '品规'},
        { field: 'matrName', title: '期初'},
        { field: 'qtyIn', title: '入库'},
        { field: 'qtyOut', title: '出库'},
        { field: 'qty9', title: '期末'}
      ]
    }
  },
  created() {
    this.getDepts()
    this.setDefaultValue()
    this.saveDailyBalance() //每次登陆实时计算
  },
  components: {
  },
  computed: {
    cpPerQueryWrapper() {
      if (this.form.id) {
        return this.$newWrapper().eq('deptDailyBalanceId', this.form.id)
          .eq('balanceDate', this.form.balanceDate)
      } else {
        return this.$newWrapper().ne(1, 1)
      }
    },
  },
  watch: {
    treeFilter(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    handleClick(tab, event) {
    },
    async loadTree() {
      await this.$ajax.get(this.treeEntry, {}).then(response => {
        if (response.code == 0) {
          response.data.forEach(o => {
            o.parentId = 0
          })
          this.treeData = global.utils.convertToTree(response.data, {
            rootNode: {id: '0', parentId: '-1', name: '所有供应商' },
            keyFieldName: 'id',
            parentFieldName: 'parentId',
            labelFieldName: 'name'
          }) // {CHECK_HERE}
          if (!this.selectedTreeNode.id) {
            this.selectedTreeNode = this.treeData[0]
          }
          this.$refs.tree.setCurrentKey(this.selectedTreeNode.id)
        } else {
          this.utilMessage.error(response.msg)
        }
      })
    },
    warehouseChange() {
      this.saveDailyBalance()
    },
    handleTreeNodeClick(data) {
      let wrapper
      if (this.form.id) {
        wrapper = data.id == 0 ? this.$newWrapper()
          : this.$newWrapper().eq('supplier_id', data.id)
        this.selectedTreeNode = data
        this.$refs.dataView.setQueryWrapper(wrapper)
        this.$refs.dv.setQueryWrapper(wrapper)
      }
    },
    getChildViewQueryWrapper() {
      if (this.form.id) {
        return this.$newWrapper().eq('dept_daily_balance_id', this.form.id)
          .eq('balance_date', this.form.balanceDate)
      } else {
        return this.$newWrapper().ne(1, 1)
      }
    },
    handleTreeFilter(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getDepts() {
      let that = this
      that.$ajax.get('/base/dept/list', {}).then((response) => {
        that.deptIds = response.data
        if (that.utils.getCurrentUser().deptDataAll) {
          that.flagAllData = false
          let all = {
            flagDefault: null,
            id: '0',
            userCode: null,
            userId: null,
            userName: null,
            warehouseCode: null,
            warehouseId: null,
            applyWarehouseId: null,
            warehouseName: '全部库存地',
            applyWarehouseName: null
          }
          that.warehouses.push(all)
        }
      })
    },
    setDefaultValue() {
      this.$ajax.get('/base/user_warehouse/getByCurrentUser').then(res => {
        if (res.code == 0) {
          this.warehouses = res.data || []
        }
      })
      this.$set(this.query, 'deptId', this.utils.getCurrentUser().deptId)
      this.$set(this.query, 'warehouseId', this.utils.getCurrentWarehouse().id)
      this.$set(this.query, 'balanceDate', new Date().format(this.dates.defaultDatePattern))
    },
    async afterLoad(rows) {
      if (this.treeData.length > 0) {
        return
      }
      await this.loadTree()
      let supplierIds = rows.map(r => r.supplierId)
      supplierIds = supplierIds.filter((item, index) => supplierIds.indexOf(item, 0) === index) //去重
      this.treeData[0].children = this.treeData[0].children.filter(item => supplierIds.indexOf(item.id, 0) > -1)
    },
    saveDailyBalance() {
      const param = {
        warehouseId: this.query.warehouseId,
        balanceDate: this.query.balanceDate
      }
      this.$ajax.post('/dept/daily_balance/save_daily_balance', param).then(response => {
        this.query.balanceDate = new Date().format(this.dates.defaultDatePattern)
        this.form = response.data
        this.$nextTick(() => {
          this.$refs.dataView.fetchData()
          this.$refs.dv.fetchData()
          this.treeSetDataLoad()
        })
      })
    },
    searchResult() {
      this.formDisabled = false
    }
  }
}
</script>

<style lang="scss" scoped>
  .container {
    height: 100%;
    background-color: #fff;
  }
  .tree-container {
    padding:10px;
    margin-right:20px;
    border:solid 1px #DCDFE6;
    height:100%
  }
  .tree-filter {
    margin:10px;
    width:80%
  }
</style>
